import axios from 'axios';
import router from '../router/index'
import { Message } from 'element-ui';
const service = axios.create({
    // process.env.NODE_ENV === 'development' 来判断是否开发环境
    // easy-mock服务挂了，暂时不使用了
    // baseURL: process.env.NODE_ENV === 'development' ? 'api/' : 'http://118.31.13.253:809/',
    baseURL: process.env.NODE_ENV === 'development' ? 'api/' : 'http://47.105.135.253:809/',
});

service.interceptors.request.use(
    config => {
        if (localStorage.getItem('Authorization')) {
            config.headers['Authorization'] = localStorage.getItem('Authorization')
        }
        for (let i in config.data) {
            if (typeof(config.data[i]) == 'string') {
                config.data[i] = config.data[i].trim()

            } else {
                config.data[i] = JSON.parse(JSON.stringify(config.data[i]).trim())
            }
        }
        return config;
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

service.interceptors.response.use(
    response => {
        // console.log(response.data.RequestStatus)
        if (response.data.RequestStatus == 200 || response.data.code == 0) {
            console.log(1)
            if (response.data.Authorization) {
                localStorage.setItem('Authorization', response.data.Authorization)
            }
            return response.data;
        } else if (response.data.RequestStatus == 401) {
            console.log(2)
            router.replace("/login")
        } else {
            Message.error(response.data.Message)
            console.log(3)
            return response.data;
        }
    },
    error => {
        console.log(error);
        return Promise.reject();
    }
);

export default service;